package com.workflow.sdk.infra.util;

import com.workflow.sdk.core.WorkflowExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Workflow execute factory
 *
 * @description: 执行策略工厂
 * @author: cyj
 * @date 2022 -07-28 11:32:13
 */
@Slf4j
public class WorkflowExecuteStrategyFactory {

    private WorkflowExecuteStrategyFactory() {
    }

    /**
     * Po status change base process map
     */
    private volatile static Map<String, WorkflowExecutor> executeMap;


    /*
     * 初始化
     * */
    public static void init() {
        if (null != executeMap) {
            return;
        }

        synchronized (WorkflowExecuteStrategyFactory.class) {

            if (null != executeMap) {
                return;
            }

            Map<String, WorkflowExecutor> executeMapTemp = WorkflowConfigurableApplicationContext.applicationContext.getBeansOfType(WorkflowExecutor.class);

            if (null != executeMapTemp) {
                executeMap = new HashMap<>();
                executeMapTemp.values().forEach(workflowExecutor -> {
                    if (StringUtils.isEmpty(workflowExecutor.getTag())) {
                        return;
                    }
                    executeMap.put(workflowExecutor.getTag(), workflowExecutor);
                });
            }
        }

    }

    /**
     * Gets bean 获取具体实例
     *
     * @param workflowCode workflow code 流程编号
     * @param nodeId       node id 需要执行流程的节点Id
     * @return the bean
     */
    public static WorkflowExecutor getExecutor(String workflowCode, Integer nodeId) {
        init();
        String tag = String.format(WorkflowExecutor.TAG, workflowCode, nodeId);
        if (!executeMap.containsKey(tag)) {
            throw new RuntimeException("workflow：" + tag + ", 未实现");
        }
        return executeMap.get(tag);
    }

}
